/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Pagination, Icon, Message, Grid, Dialog, Upload, Loading } from '@alifd/next';
import IceContainer from '@icedesign/container';
import FoundationSymbol from '@icedesign/foundation-symbol';
import IceImg from '@icedesign/img';
const TableExport = require('tableexport');
const moment = require('moment');
import axios from '../../../../instances/request';
import { withRouter } from 'react-router-dom';
import Cookies from 'universal-cookie';

const cookies = new Cookies();

import DutyShiftDialog from './DutyShiftDialog';
import DutyShiftTableFilter from './TableFilter';

const { Row, Col } = Grid;

@withRouter
export default class DutyShiftTable extends Component {
  static displayName = 'DutyShiftTable';

  static propTypes = {
    limit: PropTypes.number,
    tableConfig: PropTypes.array,
    dialogConfig: PropTypes.array,
    title: PropTypes.string,
  };

  static defaultProps = {
    limit: 8,
    tableConfig: [],
    dialogConfig: [],
    title: '',
  };

  constructor(props) {
    super(props);
    this.state = {
      __loadingVisible: false,
      search: {
        keyword: '',
        createdAtStart: null,
        createdAtEnd: null,
      },
      exportTableData: [],
      tableData: {
        totalCount: 0,
        pageSize: this.props.limit,
        currentPage: 1,
        list: [],
        __loading: false,
      },
      tableWidth: 800,
    };
  }

  async addOrUpdateDutyShift(value) {
    let url = (value.id == null || value.id === undefined) ? '/dutyShift/add' : '/dutyShift/update';
    value.type = this.props.type;
    value.fileName = (value.files && value.files.length) ? value.files[0].name: null;
    value.downloadUrl = (value.files && value.files.length) ? value.files[0].url: null;
    let res = await axios
      .post(url, {
        dutyShiftContent: value,
      }).catch((err) => {
        Message.error(`接口${err}`);
        return Promise.reject(err);
    });
    console.log("接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`接口code${code}`);
        return;
    }
  }

  async deleteDutyShift({ id }) {
    let res = await axios.post('/dutyShift/delete', {
      id,
    }).catch((err) => {
      Message.error(`删除接口${err}`);
      return Promise.reject((err));
    });
    console.log("删除接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`删除接口code${code}`);
        return;
    }
  }

  async fetchData ({ page, keyword, createdAtStart, createdAtEnd }) {
    const tableData = this.state.tableData;
    tableData.__loading = true;

    this.setState({ tableData }, async function() {
      let res = await axios.post('/dutyShift/list', {
        page: page,
        limit: this.props.limit,
        type: this.props.type,
        keyword,
        createdAtStart,
        createdAtEnd,
      }).catch((err) => {
        Message.error(`列表接口${err}`);
        return Promise.reject(err);
      });

      console.log("列表接口", res);

      let { code, msg } = res.data;
      switch (code) {
        case 0:
          let { dutyShiftList, totalCount, count } = msg;
          const tableData = this.state.tableData;
          tableData.list = dutyShiftList;
          tableData.totalCount = totalCount;
          tableData.__loading = false;
          this.setState({
            tableData
          });
          console.log(msg);
          break;
        default:
          Message.error(`列表接口code${code}`);
          return;
      }
    });
  };

  hookDutyShiftDialog(value) {
    value = value || {};
    DutyShiftDialog.show({
      dialogConfig: this.props.dialogConfig,
      value: value,
      onOk: (value) => {
        // 添加数据
        return this
          .addOrUpdateDutyShift(value)
          .then(() => {
            Message.success(value.id ? "修改成功" : '添加成功');
            DutyShiftDialog.hide();
          });
      },
      onClose: () => {
        DutyShiftDialog.hide();
      },
      onCancel: () => {
        DutyShiftDialog.hide();
      },
    });
  }

  editItem = (record, e) => {
    e.preventDefault();
    this.hookDutyShiftDialog(record);
  };

  deleteItem = (record, e) => {
    e.preventDefault();

    let dialog = Dialog.confirm({
      title: '删除确认',
      content: '您确认删除这一条目吗？',
      onOk: () => {
        return this
          .deleteDutyShift({ id: record.id })
          .then(() => {
            dialog.hide();
            Message.success("删除成功");
          });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  renderOperations = (value, index, record) => {
    return (
      <div className="operation-table-operation">
        <div>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={this.editItem.bind(this, record)}
          >
            编辑
        </span>
          <span style={styles.separator}/>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={ this.deleteItem.bind(this, record) }
          >
            删除
        </span>
        </div>
      </div>
    );
  };

  changePage = (currentPage) => {
    const { tableData, search } = this.state;
    tableData.currentPage = currentPage;
    this.setState({
      tableData
    },() => {
      this.fetchData({
        page: currentPage,
        keyword: search.keyword,
        createdAtStart: search.createdAtStart,
        createdAtEnd: search.createdAtEnd,
      });
    });
  };

  addDutyShift = () => {
    this.hookDutyShiftDialog();
  };

  setFilter({ keyword = '', createdAtStart = '', createdAtEnd = ''}){
    let search = this.state.search;
    search.keyword = keyword;
    search.createdAtStart = createdAtStart;
    search.createdAtEnd = createdAtEnd;
    this.setState({
      search,
    }, () => {
      this.fetchData({ page: 1, keyword, createdAtStart, createdAtEnd });
    })
  }

  setExportButton() {
    let tableId = 'exportTable';
    let createdAtStart = this.state.search.createdAtStart;
    let createdAtEnd = this.state.search.createdAtEnd;
    let filename = '';
    if( createdAtStart && createdAtEnd ) {
      createdAtStart = moment.unix(createdAtStart);
      createdAtEnd = moment.unix(createdAtEnd);
      filename = `${createdAtStart.year()}年`
        + `${createdAtStart.month() + 1}月`
        + `${createdAtStart.date()}日——`
        + `${createdAtEnd.year()}年`
        + `${createdAtEnd.month() + 1}月`
        + `${createdAtEnd.date()}日`;
    }
    TableExport(document.getElementById(tableId), {
      formats: ['xlsx'],
      trimWhitespace: false,
      exportButtons: true,
      filename: `${filename}${this.props.title}`,
    });
  }

  /**
   * 导出
   */
  handleExport() {
    axios.post('/dutyShift/list', {
      limit: -1,
      page: 1,
      type: this.props.type,
      keyword: this.state.search.keyword,
      createdAtStart: this.state.search.createdAtStart,
      createdAtEnd: this.state.search.createdAtEnd,
    }).then((res) => {
      let { code, msg } = res.data;
      if( code !== 0 ) {
        throw new Error(`code为${code}`);
      }
      let { dutyShiftList } = msg;
      this.setState({
        exportTableData: dutyShiftList,
      }, () => {
        this.setExportButton();
        document.getElementsByClassName('button-default xlsx')[0].click();
      });
    });
  }

  /**
   * 从Excel表格中导入数据
   */
  handleImport(files) {
    Message.loading("数据导入中");
    this.setState({
      __loadingVisible: true,
    });
    let type = this.props.type;
    let file = files[0];
    let uploader = new Upload.Uploader({
      action: '/api/file/upload',
      headers: {
        token: cookies.get('token')
      },
      onSuccess: (res) => {
        let code = res.code;
        let filename = res.msg.filename;
        if (code !== 0) {
          Message.error("导入失败");
          this.setState({
            __loadingVisible: false,
          });
          return;
        }
        axios.post('/dutyShift/analyze', {
          filename
        }).then((res) => {
          let data = res.data;
          let code = data.code;
          let dataArray = data.msg.dataArray;
          if ( code !== 0 || dataArray.length === 0 ) {
            Message.error("导入失败");
            return;
          }
          dataArray.splice(0,1);          // 删掉标题行
          return dataArray;
        }).then((dataArray) => {
          axios.post('/dutyShift/import', {
            data: dataArray,
            type: type,
          }).then((res) => {
            let data = res.data;
            let code = data.code;
            if ( code !== 0 ) {
              Message.error("导入失败");
              return;
            }
            this.fetchData({
              page: 1
            }).then(() => {
              Message.success("导入成功");
              this.setState({
                __loadingVisible: false,
              });
            });
          })
        })
      },
      onError: (err) => {
        throw new Error(err);
      }
    });
    uploader.startUpload(file);
  }

  async componentDidMount() {
    this.setState({
      tableWidth: document.body.clientWidth - 290 + 40 + 15,
    });
    await this.fetchData({
      page: 1
    });
  }

  render() {
    const tableData = this.state.tableData;

    return (
      <div className="operation-table">
        <IceContainer style={styles.cardContainer} >
          <Row>
            <Col>
              <div style={{ height: '60px', background: '#EAEBEF' }}>
                <div style={
                  {
                    float: 'left',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    height: '60px',
                    lineHeight: '60px',
                    paddingLeft: '30px',
                  }
                }>
                  <FoundationSymbol type='content' style={{ display: 'inline', verticalAlign: 'middle' }}/>
                  <span style={{ verticalAlign: 'middle' }}>&nbsp;{this.props.title}</span>
                </div>
                <div style={
                  {
                    float: 'right',
                    lineHeight: '60px',
                    marginRight: '20px',
                  }
                }>
                  <Button style={styles.addButton} type='primary' onClick={this.addDutyShift}>添加{this.props.title}</Button>
                  {
                    this.props.type !== 'dutyShift' &&
                    <Upload.Selecter style={{ display: 'inline-block', height: '32px', verticalAlign: 'middle', lineHeight: '28px' }} onSelect={this.handleImport.bind(this)}>
                      <Button className='importButton'>从Excel导入</Button>
                    </Upload.Selecter>
                  }
                  <Button
                    className='exportButton'
                    onClick={this.handleExport.bind(this)}
                  >导出到Excel</Button>
                </div>
              </div>
            </Col>
          </Row>
          <DutyShiftTableFilter setFilter={this.setFilter.bind(this)} />
          {/*// todo: 导出不能用lock，使用lock格式会很乱 */}
          <Table
            id="exportTable"
            dataSource={this.state.exportTableData}
            className="basic-table"
            hasBorder={false}
            primaryKey="key"
            style={{ textAlign: 'center', visibility:'hidden', height: '1px', width:'100%' }}
          >
            {
              this.props.tableConfig.map((col, idx) => {
                switch (col.type) {
                  case 'DateAndTime':
                    return (
                      <Table.Column
                        key={idx}
                        title={col.label}
                        dataIndex={col.name}
                        width={col.width || 150}
                        align={col.align || 'center'}
                        cell={(value, index, row) => {
                          let date = moment(row[col.name]);
                          let year = date.year();
                          let month = date.month() + 1;
                          let day = date.date();
                          let hour = date.hour();
                          hour = hour.toString().length === 1 ? `0${hour}` : hour;
                          let minute = date.minute();
                          minute = minute.toString().length === 1 ? `0${minute}` : minute;
                          return `${year}年${month}月${day}日    ${hour}:${minute}`;
                        }}
                      />
                    );
                  case 'Time':
                    return (
                      <Table.Column
                        key={idx}
                        title={col.label}
                        dataIndex={col.name}
                        width={col.width || 150}
                        align={col.align || 'center'}
                        cell={(value, index, row) => {
                          let date = moment(row[col.name]);
                          let hour = date.hour();
                          hour = hour.toString().length === 1 ? `0${hour}` : hour;
                          let minute = date.minute();
                          minute = minute.toString().length === 1 ? `0${minute}` : minute;
                          let second = date.second();
                          second = second.toString().length === 1 ? `0${second}` : second;
                          return `${hour}:${minute}:${second}`;
                        }}
                      />
                    );
                  case 'String':
                    return (
                      <Table.Column
                        key={idx}
                        title={col.label}
                        dataIndex={col.name}
                        width={col.width || 150}
                        align={col.align || 'center'}
                      />
                    );
                  case 'Table':
                    return (
                      <Table.Column
                        key={idx}
                        title={col.label}
                        width={col.width || 150}
                        align={col.align || 'center'}
                        cell={(value, index, row) => {
                          return row[col.name].map((user, idx) => {
                            if(idx % 4 === 0) {
                              return (
                                <div key={idx} style={{ border: 'none' }}>
                                  <span style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx].username}&nbsp;</span>
                                  {
                                    row.teamMembers[idx+1] &&
                                    <span style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx+1].username}&nbsp;</span>
                                  }
                                  {
                                    row.teamMembers[idx+2] &&
                                    <span style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx+2].username}&nbsp;</span>
                                  }
                                  {
                                    row.teamMembers[idx+3] &&
                                    <span style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx+3].username}&nbsp;</span>
                                  }
                                </div>
                              )
                            }
                          })
                        }}
                      />
                    );
                  case 'TextArea':
                    return (
                      <Table.Column
                        key={idx}
                        title={col.label}
                        dataIndex={col.name}
                        width={col.width || 150}
                        align={col.align || 'left'}
                        cell={(value, index, row) => {
                          return (
                            <div style={{ whiteSpace: 'pre-line' }}>
                              {
                                row[col.name]
                              }
                            </div>
                          )
                        }}
                      />
                    );
                  case 'Picture':
                    return (
                      <Table.Column
                        key={idx}
                        title={col.label}
                        lock={col.lock || false}
                        width={col.width || 150}
                        align={col.align || 'center'}
                        cell={(value, index, row) => {
                          try {
                            let url = window.location.href;
                            let arr = url.split("/");
                            return (
                              <div><a href={row.downloadUrl}>{arr[0] + "//" + arr[2]}{row.downloadUrl}</a></div>
                            );
                          } catch(err) {
                            return null;
                          }
                        }}
                      />
                    );
                    break;
                }
              })
            }
          </Table>
          <div style={{ width: this.state.tableWidth }}>
            <Table
              isZebra={true}
              dataSource={tableData.list}
              loading={tableData.__loading}
              className="basic-table"
              hasBorder={false}
              primaryKey="key"
              style={{ padding: '0 20px 20px', textAlign: 'center' }}
            >
              {
                this.props.tableConfig.map((col, idx) => {
                  switch (col.type) {
                    case 'DateAndTime':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          dataIndex={col.name}
                          lock={col.lock || false}
                          width={col.width || 150}
                          align={col.align || 'center'}
                          cell={(value, index, row) => {
                            let date = moment(row[col.name]);
                            let year = date.year();
                            let month = date.month() + 1;
                            let day = date.date();
                            let hour = date.hour();
                            hour = hour.toString().length === 1 ? `0${hour}` : hour;
                            let minute = date.minute();
                            minute = minute.toString().length === 1 ? `0${minute}` : minute;
                            return `${year}年${month}月${day}日    ${hour}:${minute}`;
                          }}
                        />
                      );
                    case 'Time':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          dataIndex={col.name}
                          lock={col.lock || false}
                          width={col.width || 150}
                          align={col.align || 'center'}
                          cell={(value, index, row) => {
                            let date = moment(row[col.name]);
                            let hour = date.hour();
                            hour = hour.toString().length === 1 ? `0${hour}` : hour;
                            let minute = date.minute();
                            minute = minute.toString().length === 1 ? `0${minute}` : minute;
                            let second = date.second();
                            second = second.toString().length === 1 ? `0${second}` : second;
                            return `${hour}:${minute}:${second}`;
                          }}
                        />
                      );
                    case 'String':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          dataIndex={col.name}
                          lock={col.lock || false}
                          width={col.width || 150}
                          align={col.align || 'center'}
                        />
                      );
                    case 'Table':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          width={col.width || 150}
                          lock={col.lock || false}
                          align={col.align || 'center'}
                          cell={(value, index, row) => {
                            return (
                              <div style={{ height: '35px', overflowY: 'auto' }}>
                                <table style={{ border: 'none', background: 'transparent' }}>
                                  <tr style={{ border: 'none' }}>
                                    <th style={{ border: 'none' }}></th>
                                    <th style={{ border: 'none' }}></th>
                                    <th style={{ border: 'none' }}></th>
                                    <th style={{ border: 'none' }}></th>
                                  </tr>
                                  <tbody>
                                  {
                                    row[col.name].map((user, idx) => {
                                      if(idx % 4 === 0) {
                                        return <tr key={idx} style={{ textAlign: 'center', border: 'none', padding: '4px 0' }}>
                                          <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx].username}&nbsp;</td>
                                          {
                                            row.teamMembers[idx + 1] &&
                                            <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx + 1].username}&nbsp;</td>
                                          }
                                          {
                                            row.teamMembers[idx + 2] &&
                                            <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx + 2].username}&nbsp;</td>
                                          }
                                          {
                                            row.teamMembers[idx + 3] &&
                                            <td style={{ border: 'none' }}>&nbsp;{row.teamMembers[idx + 3].username}&nbsp;</td>
                                          }
                                        </tr>
                                      }
                                    })
                                  }
                                  </tbody>
                                </table>
                              </div>
                            )
                          }}
                        />
                      );
                    case 'TextArea':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          lock={col.lock || false}
                          width={col.width || 150}
                          align={col.align || 'left'}
                          cell={(value, index, row) => {
                            return <div style={{ height: '44px', overflowY: 'auto', whiteSpace:'pre-line' }}>
                              {
                                row[col.name]
                              }
                            </div>
                          }}
                        />
                      );
                    case 'Bool':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          lock={col.lock || false}
                          width={col.width || 150}
                          align={col.align || 'center'}
                          cell={(value, index, row) => {
                            return row[col.name] ? '是' : '否';
                          }}
                        />
                      );
                    case 'Picture':
                      return (
                        <Table.Column
                          key={idx}
                          title={col.label}
                          lock={col.lock || false}
                          width={col.width || 150}
                          align={col.align || 'center'}
                          cell={(value, index, row) => {
                            return (
                              <a href={row.downloadUrl} target="_blank">
                                <IceImg
                                  src={row.downloadUrl}
                                  width={col.style.width}
                                  height={col.style.height}
                                />
                              </a>
                            );
                          }}
                        />
                      );
                  }
                })
              }
              <Table.Column
                title="操作"
                width={150}
                align='left'
                cell={this.renderOperations}
                lock='right'
              />
            </Table>
          </div>
          <div style={styles.paginationContainer}>
            <Pagination
              current={tableData.currentPage}
              pageSize={this.props.limit}
              total={tableData.totalCount}
              onChange={this.changePage}
              hideOnlyOnePage={false}
            />
          </div>
        </IceContainer>
        <Loading fullScreen={true} visible={this.state.__loadingVisible}/>
      </div>
    );
  }
}

const styles = {
  cardContainer: {
    padding: 0,
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  titleText: {
    marginLeft: '10px',
    lineHeight: '20px',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  paginationContainer: {
    textAlign: 'right',
    marginTop: '10px',
    paddingBottom: '10px',
    paddingRight: '20px',
  },
  operationTableTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    fontColor: 'black',
    height: '32px',
    lineHeight: '30px',
    margin: '20px 0 20px 20px',
    paddingLeft: '12px',
    borderLeft: '4px solid rgb(102, 102, 102)',
  },
  addButton: {
    marginRight: '10px',
  },
  separator: {
    margin: '0 4px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
};
